<template>
  <div class="paramConfig">
    <DFPageList ref="dfPageListRef" :pageOptions="pageOptions" />
  </div>
</template>

<script lang="ts" setup name="Order">
  import lang from './lang';
  import { listMachine } from '@/api/base/machine';
  import { pageOrder, addOrder, updateOrder, delOrder, exportOrder } from '@/api/production/order';

  import { listMaterial } from '@/api/base/material';
  import { useMixins } from '@/hooks/useMixins';
  import { startOfDay } from 'date-fns/esm';
  import { dateFn } from '@/utils/http/axios/ipcIndex';

  const { loadLangFn, getDictDataListFn, t } = useMixins();

  const dfPageListRef: any = ref(null);

  loadLangFn(lang);

  const orderStatusList = ref([]);

  const machineList = ref([]);

  const materialList = ref([]);

  const materialDetailList = ref([]);

  // 获取禁用时间 type=1禁用之前 否则禁用之后
  const getTimeDisabled = (time: number, type?: 1) => {
    const now = new Date();
    const date = new Date(time).getDate();
    const today = now.getDate();
    if (date === today) {
      const nowHour = now.getHours();
      const nowMinute = now.getMinutes();
      const nowSecond = now.getSeconds();
      return {
        isHourDisabled: (hour: number) => {
          return type ? hour < nowHour : hour > nowHour;
        },
        isMinuteDisabled: (minute: number, hour: number | null) => {
          return hour === nowHour && (type ? minute < nowMinute : minute > nowMinute);
        },
        isSecondDisabled: (second: number, minute: number | null, hour: number | null) => {
          return (
            hour === nowHour &&
            minute === nowMinute &&
            (type ? second < nowSecond : second > nowSecond)
          );
        },
      };
    }
    return true;
  };

  const getDateStr = (AddDayCount) => {
    const dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期
    const y = dd.getFullYear();
    const m = dd.getMonth() + 1; //获取当前月份的日期
    const d = dd.getDate();
    return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);
  };

  const scheduledStartTime = ref({
    createStartTime: `${getDateStr(-6)} 00:00:00`,
    createEndTime: `${getDateStr(0)} 23:59:59`,
    defaultValue: [
      new Date(`${getDateStr(-6)} 00:00:00`).getTime(),
      new Date(`${getDateStr(0)} 23:59:59`).getTime(),
    ],
  });

  const scheduledEndTime = ref({
    createStartTime: ``,
    createEndTime: ``,
    defaultValue: [],
  });

  const d = 24 * 60 * 60 * 1000;
  const disablePreviousDate = (
    ts: number,
    type: 'start' | 'end',
    range: [number, number] | null
  ) => {
    // console.log(
    //   'startOfDay(ts).valueOf() - startOfDay(range[0]).valueOf()',
    //   startOfDay(ts).valueOf() - startOfDay(range[0]).valueOf()
    // );
    if (type === 'start' && range !== null) {
      return startOfDay(range[1]).valueOf() - startOfDay(ts).valueOf() > d * 60;
    }
    if (type === 'end' && range !== null) {
      return startOfDay(ts).valueOf() - startOfDay(range[0]).valueOf() > d * 60;
    }
    return false;
  };

  // 获取当前日期对象
  const today = new Date();

  // 使用 setDate() 方法设置为昨天
  today.setDate(today.getDate() - 1);

  // 将时间设置为23:59:59.999
  today.setHours(23, 59, 59, 999);

  // 获取时间戳
  const timestamp = today.getTime();

  const pageOptions = {
    searchForm: {
      formSchemas: [
        {
          label: 'fastSearch',
          component: 'NInput',
          componentProps: {
            placeholder: t('order.table.plInput'),
          },
        },
        {
          label: 'orderStatusName',
          prop: 'orderStatusCode',
          component: 'NSelect',
          options: orderStatusList,
        },
        {
          label: 'scheduledStartTime',
          component: 'NDatePicker',
          defaultValue: null,
          componentProps: {
            clearable: true,
            type: 'datetimerange',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            format: 'yyyy-MM-dd HH:mm:ss',
            defaultTime: ['00:00:00', '23:59:59'],
            isDateDisabled: disablePreviousDate,
            onUpdateValue: (_, v: string[]) => {
              if (v) {
                scheduledStartTime.value.createStartTime = v[0];
                scheduledStartTime.value.createEndTime = v[1];
              } else {
                scheduledStartTime.value.createStartTime = '';
                scheduledStartTime.value.createEndTime = '';
              }
            },
          },
        },
        {
          label: 'scheduledEndTime',
          component: 'NDatePicker',
          componentProps: {
            clearable: true,
            type: 'datetimerange',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            format: 'yyyy-MM-dd HH:mm:ss',
            defaultTime: ['00:00:00', '23:59:59'],
            isDateDisabled: disablePreviousDate,
            onUpdateValue: (_, v: string[]) => {
              if (v) {
                scheduledEndTime.value.createStartTime = v[0];
                scheduledEndTime.value.createEndTime = v[1];
              } else {
                scheduledEndTime.value.createStartTime = '';
                scheduledEndTime.value.createEndTime = '';
              }
            },
          },
        },
        {
          label: 'machineName',
          prop: 'machineCode',
          component: 'NSelect',
          options: machineList,
        },
        {
          label: 'customerNo',
          component: 'NInput',
        },
        {
          label: 'customerOrderNo',
          component: 'NInput',
        },
      ],
    },
    table: {
      hasSelection: true,
      columns: [
        {
          width: 120,
          label: 'machineName',
        },
        {
          width: 120,
          label: 'materialName',
        },
        {
          width: 120,
          label: 'version',
        },
        {
          width: 200,
          label: 'orderCode',
        },
        {
          width: 120,
          label: 'orderNum',
        },
        {
          width: 120,
          label: 'paperboardNum',
        },
        {
          width: 120,
          label: 'orderStatusName',
        },
        {
          width: 120,
          label: 'proOrder',
        },
        {
          width: 180,
          label: 'scheduledStartTime',
          render: (row) => {
            return h('span', {
              innerText: row.scheduledStartTime ? dateFn(new Date(row.scheduledStartTime)) : '-',
            });
          },
        },
        {
          width: 180,
          label: 'scheduledEndTime',
          render: (row) => {
            return h('span', {
              innerText: row.scheduledEndTime ? dateFn(new Date(row.scheduledEndTime)) : '-',
            });
          },
        },
        {
          width: 120,
          label: 'customName',
        },
        {
          width: 120,
          label: 'customerNo',
        },
        {
          width: 120,
          label: 'customerOrderNo',
        },
        {
          width: 180,
          label: 'customerDeliveryDate',
          render: (row) => {
            return h('span', {
              innerText: row.customerDeliveryDate
                ? dateFn(new Date(row.customerDeliveryDate))
                : '-',
            });
          },
        },
        {
          width: 120,
          label: 'erpNo',
        },
        {
          width: 120,
          label: 'remark',
          common: true,
        },
      ],
      action: {
        columns: [
          {
            label: 'check',
          },
          {
            label: 'delete',
          },
        ],
      },
      operaColumn: [
        {
          label: 'add',
        },
        {
          label: 'export',
        },
      ],
      requestFn: pageOrder,
      delRequestFn: delOrder,
      exportRequestFn: exportOrder,
    },
    modalFormDialog: {
      formSchemas: [
        {
          label: 'machineName',
          prop: 'machineCode',
          required: true,
          component: 'NSelect',
          options: machineList,
        },
        {
          label: 'materialName',
          required: true,
          component: 'NSelect',
          options: materialList,
          prop: 'materialId',
          checkProp: 'materialName',
        },
        {
          label: 'orderNum',
          required: true,
          requiredRulesType: 'number',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 1,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'paperboardNum',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 1,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'scheduledDebugTime',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 1,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'scheduledProductTime',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 1,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'scheduledStartTime',
          component: 'NDatePicker',
          defaultValue: null,
          componentProps: {
            clearable: true,
            format: 'yyyy-MM-dd HH:mm',
            type: 'datetime',
            'is-date-disabled': (time: number) => {
              return time < timestamp;
            },
            'is-time-disabled': (time: number) => {
              return getTimeDisabled(time, 1);
            },
          },
          checkPropFn: (row) => {
            return row.scheduledStartTime ? dateFn(new Date(row.scheduledStartTime)) : '-';
          },
        },
        {
          label: 'scheduledEndTime',
          component: 'NDatePicker',
          componentProps: {
            clearable: true,
            format: 'yyyy-MM-dd HH:mm',
            type: 'datetime',
            'is-date-disabled': (time: number) => {
              return time < timestamp;
            },
            'is-time-disabled': (time: number) => {
              return getTimeDisabled(time, 1);
            },
          },
          checkPropFn: (row) => {
            return row.scheduledEndTime ? dateFn(new Date(row.scheduledEndTime)) : '-';
          },
        },
        {
          label: 'customerOrderNo',
        },
        {
          label: 'customerDeliveryDate',
          component: 'NDatePicker',
          componentProps: {
            clearable: true,
            format: 'yyyy-MM-dd HH:mm',
            type: 'datetime',
          },
          span: 3,
          checkPropFn: (row) => {
            return row.customerDeliveryDate ? dateFn(new Date(row.customerDeliveryDate)) : '-';
          },
        },
        {
          label: 'erpNo',
          component: 'NInput',
        },
        {
          label: 'proOrder',
          component: 'NInputNumber',
          defaultValue: 0,
          required: true,
          requiredRulesType: 'number',
          componentProps: {
            maxlength: 50,
            min: 0,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'remark',
          common: true,
          type: 'textarea',
          span: 3,
          giProps: { span: 4 },
        },
      ],
      descriptionsListLabelWidthZh: 160,
      cols: 2,
      addDataFn: addOrder,
      updateDataFn: updateOrder,
      setDialogSubmitDataFn: (data) => {
        const { materialId } = data;

        const obj = materialDetailList.value.find((item) => item.id === materialId);

        const newData = {
          ...data,
          ...obj,
          materialRemark: obj.remark,
          remark: data.remark,
        };

        delete newData.createTime;

        delete newData.updateTime;

        delete newData.id;

        return newData;
      },
    },
  };

  const initDictData = async () => {
    const res = await Promise.all([
      getDictDataListFn('order_status'),
      listMachine(),
      listMaterial(),
    ]);

    const [list1, res2, res3] = res;

    orderStatusList.value = list1;

    machineList.value =
      res2?.data.map((item) => ({ label: item.machineName, value: item.machineCode })) || [];

    materialDetailList.value = res3.data;

    materialList.value =
      res3?.data.map((item) => ({
        label: `${item.materialName}(${item.version})`,
        value: item.id,
      })) || [];
  };

  initDictData();

  // nextTick(() => {
  //   dfPageListRef.value && dfPageListRef.value.openModalFn();
  // });
</script>
